<?php

class Globals
 {
	/**
     * cache object
     * db object
     * @var object
     */
	private static $_cache 	= null;
	private static $_dbName = null;
	private static $_db 	= null;

	public static $arrDB = array();
	
	static public function getConfiguration()
	{
		return Zend_Registry::get('configuration');
	}

	/*
	 * method for partition db by userid
	 */
       public static function setDbByUserId($userId, $dbName='', $maxUserId='')
       {

	      if($dbName != '' && $maxUserId != '')
	      {
		     $part 	= (int)($userId/$maxUserId);
		     $dbName 	= empty($part)?$dbName:$dbName.$part;
		     return $dbName;
	      }
	      else
	      {
		     $globalConfig 	= Zend_Registry::get('configuration');
		     $maxUserId 	= $globalConfig->profile->dbmaxrecord;
		     return self::setDbByUserId($userId,'profile',$maxUserId);
	      }
       }

       public static function getPartitionNumber($userId)
       {
	      $globalConfig 		= Zend_Registry::get('configuration');
	      $maxUserId 		= $globalConfig->profile->dbmaxrecord;
	      $part 			= (int)($userId/$maxUserId);
	      $part 			= empty($part)?'':$part;

	      return $part;
       }


       /*
	* method for partition table by userid
	*/
       public static function setTblByUserId($userId, $tblName, $maxUserId)
       {
	      $part 	= (int)($userId/$maxUserId);
	      $tblName = empty($part)?$tblName:$tblName.$part;

	      return $tblName;
       }

       /*
	* method for partition table friend
	*/
       public static function getFriendTable($userid)
       {
	      $globalConfig 	= Zend_Registry::get('configuration');
	      $maxFriendUserId 	= $globalConfig->friend->maxuserid;
	      $tblName 		= Globals::setTblByUserId($userid, 'friends', $maxFriendUserId);

	      return $tblName;
       }

       /*
	* method for set db name
	*/
       public static function setDbName($dbName)
       {
	      self::$_dbName = $dbName;
	      return self::$_dbName;
       }

       /*
	* method for get db name
	*/
       public static function getDbName()
       {
	       return self::$_dbName;
       }

       public static function getCache()
       {
	       return self::getPureMemcache();
       }

       public static function dumpLog($content)
       {

			if(Zend_Registry::isRegistered('logger'))
            {
				$logger = Zend_Registry::get('logger');
				$logger->log($content, Zend_Log::EMERG);
			}
			else
			{
				$configuration = Zend_Registry::get("configuration");
                		$logger = new Zend_Log();
				$logger->addWriter(new Zend_Log_Writer_Stream($configuration->common->log->path));
				Zend_Registry::set('logger', $logger);
				$logger->log($content, Zend_Log::EMERG);
			}
       }

       public static function isDebug()
       {
          if (SGN_Application::isInternalUser()) {
              $debug = true;
          }
          return $debug;
		  if(!isset($_REQUEST['debug'])) return false;
	      $debug = $_REQUEST['debug'];
	      if(isset($_REQUEST['debug']) && $debug != null && $debug == "true") return true;
	      else return false;
       }

       public static function getPureMemcache()
       {
	      if(self::$_cache != null)
	      {
		      return self::$_cache;
	      }
	      $globalConfig = Zend_Registry::get('configuration');

	      self::$_cache = MyMemcache::factory($globalConfig->cache->memcache->host,$globalConfig->cache->memcache->port);
	      return self::$_cache;

       }

       public static function closeAllDbConnection()
       {
       		if(is_array(self::$arrDB) && count(self::$arrDB) > 0)
       		{
	       		foreach(self::$arrDB as $key => $value)
	       		{
	       			if($value != null) $value->closeConnection();
	       		}
       		}

       }

       public static function checkModuleEnable($module = '')
       {
       		if($module == '') return true;
       		$config = Zend_Registry::get('configuration');

       		$config = Zend_Registry::get('configuration');

       		if(isset($config->module_enable))
       		{
       			if($config->module_enable->$module == false) return false;
       			else return true;
       		}
       		else
       		{
       			return true;
       		}

       }

       public static function getDbConnection1($dbName, $state, $iniConfigFile)
       {
	      if (self::$_db != null && $state)
	      {
		      return self::$_db;
	      }

	      if(isset(self::$arrDB[$dbName]) && self::$arrDB[$dbName] != null)
	      {
		      self::$_db = self::$arrDB[$dbName];
		      return self::$arrDB[$dbName];
	      }

	      $config = Zend_Registry::get('configuration');

	      $_db = Zend_Db::factory($config->$dbName);

	      $debug = Globals::isDebug();

	      if($debug == true)
	      {
		      $_db->getProfiler()->setEnabled(true);
	      }


	      //$_db->query('SET NAMES UTF8');
	      self::$arrDB[$dbName] = $_db;
	      self::$_db = $_db;
	      return $_db;
       }

       /*
	* method for get db cache
	* var $state : for check if db name is changed
	* $state = false = changed to another db
        * @return Zend_Db
	*/
       public static function getDbConnection($dbName = 'maindb', $state = true, $iniConfigFile = '')
       {
	      //if($_SERVER['REMOTE_ADDR']== "10.199.36.106")
	      if(true)
	      {
		      return self::getDbConnection1($dbName,$state,$iniConfigFile);
	      }

	      if (self::$_db != null && $state)
	      {
		      return self::$_db;
	      }

	      $config = Zend_Registry::get('configuration');

	      self::$_db = Zend_Db::factory($config->$dbName);
	      //self::$_db->setFetchMode(Zend_Db::FETCH_ASSOC);
	      // set Collation = utf8
	      self::$_db->query('SET NAMES UTF8');
	      return self::$_db;
       }

       public static function enableProfiler($db)
       {
	       $db->getProfiler()->setEnabled(true);
       }

       public static function disableProfiler($db)
       {
	       $db->getProfiler()->setEnabled(true);
       }

       public static function filterAlphabet($var)
       {
	       if(substr(ucfirst($var['displayname']), 0, 1) == 'C')
	       {
		       return $var;
	       }
       }

       //use for debug
       //author : tunm
       public static function checkIPDebug($ips = array('10.199.36.18','10.199.25.42','10.199.55.82','10.199.21.25', '10.199.36.103'))
       {
		   if(!is_array($ips))
			   $ips = array($ips);
		   foreach($ips as $ip)
		   {
			   if( $_SERVER['REMOTE_ADDR'] == $ip)
				return true;
		   }
		   return false;
       }

       /**
	* utf8 to ascii
	*/
       static function utf8ToAscii($str)
       {
	       $chars = array
	       (
		       'a' => array('Ấ','Ầ','Ẩ','Ẫ','Ậ','Ắ','Ằ','Ẳ','Ẵ','Ặ','Á','À','Ả','Ã','Ạ','Â','Ă'),
		       'e' => array('Ế','Ề','Ể','Ễ','Ệ','ê','É','È','Ẻ','Ẽ','Ẹ','Ê'),
		       'i' => array('Í','Ì','Ỉ',' Ĩ','Ị'),
		       'o' => array('Ố','Ồ','Ổ','Ố','Ộ','Ớ','Ờ','Ở','Ỡ','Ợ','Ó','Ò','Ỏ','Õ','Ọ','Ô','Ơ'),
		       'u' => array('Ứ','Ừ','Ữ','Ữ','Ự','Ù','Ủ','Ũ','Ụ','Ư'),
		       'y' => array('Ý','Ỳ','Ỷ ','Ỹ','Ỵ'),
		       'd' => array('Đ'),
	       );

	       foreach ($chars as $key => $arr)
	       {
		       foreach ($arr as $val)
		       {
			       $str = str_replace($val, $key, $str);
			       return $str;
		       }
	       }
       }

       /**
	* get all city from 'maindb' - data_country table
	* @countryid
	* return @array
	*/
       static function getCities($countryId = 1)
       {
	     $key = "data_city-" . $countryId;
	     $result = GlobalCache::getCache($key);

	     if($result == null )
	     {
		    $db 	= self::getDbConnection('maindb',false);

		    //1. build where
		    $where = '';
		    $countryId = trim($countryId);

		    if( !empty($countryId) )
		    {
			   $where .= ' WHERE countryid = ' . intval($countryId);
		    }
		    else
		    {
			   $where .= ' WHERE countryid = 1';
		    }

		    // 2. build select
		    $query = " SELECT * FROM data_city $where"
				   ." ORDER BY ordering ASC";

		    $result = $db->fetchAll($query);
		    if($result != null && is_array($result))
		    {
			   GlobalCache::setCache($key,$result);
		    }
	     }

	     return self::resultToArray($result);
       }

       static function getCityNameByCityId($cityId = '')
       {
	     if ($cityId == '') return NULL;

//	     $key = "name_city-" . $cityId;
	     $result = GlobalCache::getCache($key);

	     if ($result == NULL)
	     {
		  // setup db name
		  $db 	= self::getDbConnection('maindb',false);

		  $where = ' WHERE id = ' . $cityId;
		  $query = " SELECT name FROM data_city $where";

		  $result = $db->fetchAll($query);
		  if($result != null && is_array($result))
		  {
			  GlobalCache::setCache($key,$result);
		  }

	     }

	     if(is_array($result) && (count($result) > 0) && isset($result[0]))
	     {
		    return $result[0]['name'];
	     }

	     return NULL;
       }

		static function getCityByCityIdCountryId($cityId = '', $countryId = '')
		{
			if($cityId == '' || $countryId == '')
			{
			     return NULL;
			}
			$key = "data_city-" . $countryId ."-" .$cityId;
			$result = GlobalCache::getCache($key);

			if($result == null )
			{
			     // setup db name
				$db 	= self::getDbConnection('maindb',false);
				$result 	= null;

				$where = ' WHERE id = ' . intval($cityId) . ' AND countryid = ' . intval($countryId);
				$query = " SELECT name FROM data_city $where";


				$result = $db->fetchAll($query);
				if($result != null && is_array($result))
				{
					GlobalCache::setCache($key,$result);
				}
			}

		    if( isset($result[0]))
		    {
			     return $result[0]['name'];
		    }
	   }

       /**
	* get all district from 'maindb' - data_district table
	* @cityid
	* return @array
	*/
       static function getDistrict($cityId = '')
       {
	      $key = "district-list-" . $cityId;
	      $result = GlobalCache::getCache($key);
	      if($result == null )
	      {
		     // setup db name
		     self::setDbName('dbmain');
		     $db 	= self::getDbConnection(false);
		     $result = null;

		     $where = '';
		     if($cityId != '')
		     {
			     $where .= ' WHERE cityid = ' . $cityId;
		     }

		     // no cache
		     $query = "SELECT * FROM data_district $where ORDER BY ordering ASC";

		     $result = $db->fetchAll($query);
		     if($result != null && is_array($result))
		     {
			   GlobalCache::setCache($key, $result);
		     }
		     else
		     {
			    return array();
		     }
	      }

	      return self::resultToArray($result);
       }

       /**
	* get all income from 'maindb' - data_income table
	* return @array
	*/
       static function getArrByTblName($tblName = '', $getArr=true)
       {
	       $result = null;
	       if($tblName != '')
	       {
		       // GET cache
		       $key = "all-" . $tblName;
		       $result = GlobalCache::getCache($key);

		       if($result == null )
		       {
			       $query = " SELECT * FROM {$tblName}"
					       ." ORDER BY ordering ASC";
		       	   // setup db name
			       $db 	= self::getDbConnection('maindb', false);

			       $result = $db->fetchAll($query);
			       if($result != null && is_array($result))
			       {
				       GlobalCache::setCache($key,$result);
			       }
		       }
		       if( $getArr )
		       {
		       	return self::resultToArray($result);
		       }
	       }


	       return $result;
       }

       /**
	* convert array result resource to array
	*/
       static function resultToArray($result)
       {
	       $arrTmp = array();

	       if (is_array($result) && (count($result) > 0))
	       {
		    foreach($result as $key => $value)
		    {
			    $arrTmp[$value['id']] = $value['name'];
		    }
	       }
	       return $arrTmp;
       }

       /**
	* method: doPaging
	* paging data
	* @return paginator object
	*/
       static function doPaging($arrData, $page, $view)
       {
	       // get paging configuration
       $config = Zend_Registry::get('configuration');
	       $arrPaging = $config->pagination->toArray();
       $paginator  = Zend_Paginator::factory($arrData);
       $paginator->setCurrentPageNumber($page)
		 ->setItemCountPerPage(50)
		 ->setPageRange($arrPaging['pageRange']);
	       $viewRenderer = Zend_Controller_Action_HelperBroker
					::getStaticHelper('viewRenderer');
	       // setup view helpers
	       //$view->setScriptPath(APPLICATION_PATH . '/modules/admin/views/scripts/');
	       $viewRenderer->setView($view);
       $viewRenderer->view->paginator      = $paginator;
       $viewRenderer->view->currentPage    = $page;
       $viewRenderer->view->scrollingStyle = $arrPaging['scrollingStyle'];
       Zend_View_Helper_PaginationControl::setDefaultViewPartial(
       'common/' . $arrPaging['paginationControl'] . '_pagination_control.phtml');
       }

       /**
	* method for partition table by userid
	* @author Tình UGC
	*/
       public static function setTblByAlbumId($albumId, $tblName, $maxTable)
       {
	       $part 	= (int)($albumId%$maxTable);
       $tblName = empty($part)?$tblName:$tblName.$part;
	       return $tblName;
       }

       /**
	* method for partition table photo
	* @author Tình UGC
	*/
       public static function getPhotoTable($albumId)
       {
	       $globalConfig 	= Zend_Registry::get('configuration');
	       $maxTable 	= $globalConfig->photo->maxtable;
	       $tblName 			= Globals::setTblByAlbumId($albumId, 'images', $maxTable);
	       return $tblName;
       }

       /**
       * Get school names
       * @param int schoolcateId
       * @param int cityId
       * @param int countryId=1
       * @return array schoolname
       * @author mynnt
       * @date Jul 9, 2009
       */
       public static function getSchoolnames( $cateId = 0, $cityId = 1, $countryId = 1 )
       {
	       $key = 'allschool-' . $cateId . '-' . $cityId . '-' . $countryId;
	       $result = GlobalCache::getCache( $key );
	       //Return value
	       if($result == null )
	       {
		       //Connect DB
		       $db = self::getDbConnection('maindb',false);

		       //Initiate the result value
		       $result = null;

		       //Query
		       $query = "SELECT * ".
					" FROM data_school ".
					" WHERE countryid = 1 ".
						       " AND cityid = ".intval( $cityId ).
						       " AND schoolcateid = ".intval( $cateId ).
					 " ORDER BY schoolname ASC";

		       $result = $db->fetchAll($query);
		       if($result != null && is_array($result))
		       {
			       GlobalCache::setCache($key,$result);
		       }
	       }
	       return $result;
       }

       /**
	* Get list of district
	* @param cityId
	* @return list of district
	* @author mynnt
	* @date Jul 10, 2009
       */
       public static function getListDistricts( $cityId = -1 )
       {
	      $ret = array( '' => '--' );

	      //1. Check input
	      if( $cityId <= 0 || is_numeric( $cityId ) == FALSE )
	      {
		      return $ret;
	      }

	      //2. get data from cache
	      $key = "district-" . $cityId;
	      var_dump($key);
	      $result = GlobalCache::getCache($key);

	      if ( $result  == NULL)
	      {
		     //Get data from DB
		     $db = self::getDbConnection('maindb',false);

		     //Query
		     $query = "SELECT * ".
				      " FROM data_district ".
				      " WHERE cityid = ".intval( $cityId ).
				       " ORDER BY ordering ASC";
		     $result = $db->fetchAll($query);

		     if($result != null && is_array($result))
		     {
			    GlobalCache::setCache($key,$result);
		     }
	      }

	      // 3. return data
	      return $result;
       }

       /**
	* Get list of company
	* @return list of company
	* @author mynnt
	* @date Jul 10, 2009
       */
       public static function getListCompany()
       {
	      $key = "lc_company";
	      $result = GlobalCache::getCache( $key );
	      if($result == null )
	      {
		     //Connect DB
		     $db = self::getDbConnection('maindb',false);

		     //Query
		     $query = "SELECT * ".
				      " FROM data_company ".
				      " ORDER BY ordering ASC";

		     //Execute query
		     $result = $db->fetchAll($query);
		     if($result != null && is_array($result))
		     {
			     GlobalCache::setCache($key,$result);
		     }
	      }
	      return $result;
       }
	   
	   static public function getBaseUrl() {
		$configuration = Zend_Registry::get('configuration');
		if (isset($configuration->baseurl)) {
			return $configuration->baseurl;
		}
		else
			return "/";
	}
}

?>
